package com.wushi.lenovo.asia5b.app_ui.login.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.ListPopupWindow;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mvp.base.BaseMvpActivity;
import com.mvp.base.model.ResultModel;
import com.mvp.common.GlobalValue;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.login.mvpview.RegisterActivityView;
import com.wushi.lenovo.asia5b.app_di.login.presenter.RegisterActivityPresenter;
import com.wushi.lenovo.asia5b.app_di.other.presenter.CodePresenter;
import com.wushi.lenovo.asia5b.app_model.other.WebUrlType;
import com.wushi.lenovo.asia5b.app_model.profile.CodeModel;
import com.wushi.lenovo.asia5b.app_model.profile.CountryModel;
import com.wushi.lenovo.asia5b.app_model.profile.ValidModel;
import com.wushi.lenovo.asia5b.app_push.PushHelper;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupListAdapter;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupWindowHelper;
import com.wushi.lenovo.asia5b.app_widget.ErrorTextView;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import timber.log.Timber;

/**
 * Created by zhangyuncai on 2018/11/28.
 * 注册
 */
public class RegisterActivity extends BaseMvpActivity<RegisterActivityView, RegisterActivityPresenter> implements RegisterActivityView {
    @BindView(R.id.et_register_email)
    EditText et_register_email;
    @BindView(R.id.tv_register_countryname)
    TextView tv_register_countryname;
    @BindView(R.id.et_register_code)
    EditText et_register_code;
    @BindView(R.id.tv_register_getcode)
    TextView tv_register_getcode;
    @BindView(R.id.et_register_pass)
    EditText et_register_pass;
    @BindView(R.id.et_register_passagain)
    EditText et_register_passagain;
    @BindView(R.id.bt_register_submit)
    Button bt_register_submit;
    @BindView(R.id.ll_register_country)
    LinearLayout ll_register_country;
    @BindView(R.id.tv_register_areacode)
    TextView tv_register_areacode;
    @BindView(R.id.et_register_phone)
    EditText et_register_phone;
    @BindView(R.id.tv_register_code_error)
    ErrorTextView tv_register_code_error;
    @BindView(R.id.tv_termsofuse)
    TextView tv_termsofuse;//使用条款
    @BindView(R.id.tv_privacypolicy)
    TextView tv_privacypolicy;//隐私政策
    private final List<String> countryNameList = new ArrayList<>();
    @BindView(R.id.iv_register_eye1)
    ImageView iv_register_eye1;
    @BindView(R.id.iv_register_eye2)
    ImageView iv_register_eye2;
    @BindView(R.id.tv_register_mobile_error)
    ErrorTextView tv_register_mobile_error;
    @BindView(R.id.tv_register_email_error)
    ErrorTextView tv_register_email_error;
    @BindView(R.id.tv_register_pass_error)
    ErrorTextView tv_register_pass_error;
    private PopupListAdapter<CountryModel> popupListAdapter;
    private ListPopupWindow popupWindow;
    private final Set<String> registeredEmails = new HashSet<>();//无效集合
    private final Set<String> registeredMobiles = new HashSet<>();//无效集合

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();

        initData();

        initEvent();
    }

    @Override
    protected void initView() {
        initPopupWindow();
        setLocalTextView();
    }

    private void setLocalTextView() {
        EyeUtils.setLinkText(this, getString(R.string.register_termsofuse_1), getString(R.string.termsofuse2),
                tv_termsofuse, WebUrlType.termsofuse);
        EyeUtils.setLinkText(this, getString(R.string.register_privacypolicy_1), getString(R.string.register_privacypolicy_2),
                tv_privacypolicy, WebUrlType.privacypolicy);
    }

    private void initPopupWindow() {
        popupListAdapter = new PopupListAdapter<>(this, R.layout.item_popupitem_login_adapter);
        popupWindow = PopupWindowHelper.getListPopupWindow(this, popupListAdapter
                , ll_register_country, ListPopupWindow.WRAP_CONTENT);
    }

    @Override
    protected void initData() {
        getPresenter().getCountrys();
    }

    private void submit() {
        boolean b = false;
        //邮箱
        String email = et_register_email.getText().toString().trim();
        //国家
        int countryId = -1;
        CountryModel selectCountryModel = popupListAdapter.getSelectItem();
        if (selectCountryModel != null) {
            countryId = selectCountryModel.getId();
        }
        //手机号
        String phone = et_register_phone.getText().toString().trim();
        //密码
        String pass = et_register_pass.getText().toString().trim();
        //确认密码
        String passSure = et_register_passagain.getText().toString().trim();
        //验证码
        String code = et_register_code.getText().toString().trim();


        if (TextUtils.isEmpty(email)) {
            b = true;
            tv_register_email_error.setText(R.string.filed_is_empty);
            tv_register_email_error.setVisibility(View.VISIBLE);
        } else if (registeredEmails.contains(email)) {
            b = true;
            tv_register_email_error.setText(R.string.register_email_error);
            tv_register_email_error.setVisibility(View.VISIBLE);
        }
        if (countryId <= 0) {
            tv_register_mobile_error.setText(R.string.filed_is_empty);
            tv_register_mobile_error.setVisibility(View.VISIBLE);
            b = true;
        }
        if (TextUtils.isEmpty(phone)) {
            tv_register_mobile_error.setText(R.string.filed_is_empty);
            tv_register_mobile_error.setVisibility(View.VISIBLE);
            b = true;
        } else if (registeredMobiles.contains(phone)) {
            tv_register_mobile_error.setText(R.string.register_mobile_error);
            tv_register_mobile_error.setVisibility(View.VISIBLE);
            b = true;
        }
        if (TextUtils.isEmpty(pass)) {
            tv_register_pass_error.setText(R.string.filed_is_empty);
            tv_register_pass_error.setVisibility(View.VISIBLE);
            b = true;
        } else if (!TextUtils.equals(pass, passSure)) {
            tv_register_pass_error.setText(R.string.register_pass_error);
            tv_register_pass_error.setVisibility(View.VISIBLE);
            b = true;
        }
        if (TextUtils.isEmpty(code)) {
            b = true;
            tv_register_code_error.setText(R.string.filed_is_empty);
            tv_register_code_error.setVisibility(View.VISIBLE);
        } else {
            Object tag = et_register_code.getTag();
            if (tag != null && tag instanceof String) {
                String requestCode = (String) tag;
                if (!TextUtils.equals(requestCode, code)) {
                    tv_register_code_error.setText(R.string.invalid_code);
                    tv_register_code_error.setVisibility(View.VISIBLE);
                    b = true;
                }
            }
        }
        if (b) {
            return;
        }
        Map<String, Object> map = MapHelper.newHashMap();
        map.put("email", email);
        map.put("mobile", phone);
        map.put("password", pass);
        map.put("country_id", countryId);
        map.put("otp", code);
        map.put("app_register_id", "" + PushHelper.getRegistrationId());
        map.put("app_os", 1);//1 = Android , 2 = IOS
        getPresenter().register(map);
    }

    private void sendCode() {
        String phone = et_register_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            tv_register_mobile_error.setText(R.string.filed_is_empty);
            tv_register_mobile_error.setVisibility(View.VISIBLE);
            return;
        }
        CountryModel selectCountryModel = popupListAdapter.getSelectItem();
        if (selectCountryModel == null) {
            return;
        }
        getPresenter().sendCode(phone, selectCountryModel.getCalling_code());
    }


    @Override
    protected void initEvent() {
        tv_register_mobile_error.setBindEditText(et_register_phone);
        tv_register_email_error.setBindEditText(et_register_email);
        tv_register_pass_error.setBindEditText(et_register_pass, et_register_passagain);
        tv_register_code_error.setBindEditText(et_register_code);
        popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
                popupListAdapter.setSelectPosition(position);
                CountryModel selectCountryModel = popupListAdapter.getSelectItem();
                if (selectCountryModel != null) {
                    tv_register_countryname.setText(selectCountryModel.getName());
                    tv_register_areacode.setText("+" + selectCountryModel.getCalling_code());
                }
            }
        });
        et_register_email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    String email = et_register_email.getText().toString();
                    if (!TextUtils.isEmpty(email)) {
                        if (email.contains("@")) {
                            getPresenter().checkEmailByRegister(email);
                        }
                    }
                }
            }
        });
        et_register_phone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    String mobile = et_register_phone.getText().toString();
                    if (!TextUtils.isEmpty(mobile)) {
                        int countryId = -1;
                        CountryModel selectCountryModel = popupListAdapter.getSelectItem();
                        if (selectCountryModel != null) {
                            countryId = selectCountryModel.getId();
                            if (countryId > 0) {
                                getPresenter().checkMobileByRegister(mobile, countryId + "");
                            }
                        }

                    }
                }
            }
        });
        et_register_passagain.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    //密码
                    String pass = et_register_pass.getText().toString().trim();
                    //确认密码
                    String passSure = et_register_passagain.getText().toString().trim();
                    if (!TextUtils.isEmpty(pass) && !TextUtils.isEmpty(passSure) && !TextUtils.equals(pass, passSure)) {
                        tv_register_pass_error.setText(R.string.register_pass_error);
                        tv_register_pass_error.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
        et_register_pass.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    //密码
                    String pass = et_register_pass.getText().toString().trim();
                    //确认密码
                    String passSure = et_register_passagain.getText().toString().trim();
                    if (!TextUtils.isEmpty(pass) && !TextUtils.isEmpty(passSure) && !TextUtils.equals(pass, passSure)) {
                        tv_register_pass_error.setText(R.string.register_pass_error);
                        tv_register_pass_error.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
        EyeUtils.bindEye(iv_register_eye1, et_register_pass);
        EyeUtils.bindEye(iv_register_eye2, et_register_passagain);
    }

    @Override
    @OnClick({
            R.id.bt_register_submit,
            R.id.ll_register_country,
            R.id.tv_register_getcode
    })
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_register_submit: {
                submit();
            }
            break;
            case R.id.ll_register_country: {
                PopupWindowHelper.showPopupWindow(popupWindow);
            }
            break;
            case R.id.tv_register_getcode: {
                et_register_code.setTag("");
                sendCode();
            }
            break;
        }
    }

    @Override
    public void getCountrysResult(List<CountryModel> countryModels) {
        List<CountryModel> data = countryModels;
        popupListAdapter.setDatas(data);
        if (data != null && data.size() != 0) {
            et_register_phone.setEnabled(true);
            popupListAdapter.setSelectPosition(0);
            CountryModel selectCountryModel = popupListAdapter.getSelectItem();
            if (selectCountryModel != null) {
                tv_register_countryname.setText(selectCountryModel.getName());
                tv_register_areacode.setText("+" + selectCountryModel.getCalling_code());
            }
        }
    }


    @Override
    public void sendCodeResult(ResultModel<CodeModel> resultModel, CodePresenter.CodeType codeType) {
        if (resultModel != null && resultModel.isSuccess()) {
            ToastUtil.showToast(getString(R.string.otp_send_success));
            getPresenter().interval();

            CodeModel codeModel = resultModel.getData();
            if (codeModel != null) {
                String resultCode = codeModel.getOTP_code();
                et_register_code.setTag(resultCode);
                if (GlobalValue.isDebug) {
                    et_register_code.setText(resultCode);
                }
            }
        }
    }

    @Override
    public void intervalResult(long aLong) {
        Timber.d("--->>>>>>>>---aLong:" + aLong);
        if (aLong == 0) {
            tv_register_getcode.setEnabled(true);
            tv_register_getcode.setText(R.string.chongxinhuoquyanzhengma);
        } else {
            tv_register_getcode.setEnabled(false);
            tv_register_getcode.setText(aLong + "s");
        }
    }


    /**
     *
     * @param toastMsgMap 1->注册成功 2->注册失败 3->登录失败 4->登录成功
     */
    @Override
    public void registerResult(Map<Integer, String> toastMsgMap) {
        if (toastMsgMap.containsKey(1)&&toastMsgMap.containsKey(4)) {//注册成功且登录成功
            ToastUtil.showToast(toastMsgMap.get(1));
            finish();
        } else if (toastMsgMap.containsKey(1)&&toastMsgMap.containsKey(3)) {//注册成功但登录失败
            ToastUtil.showToast(toastMsgMap.get(1));
            startActivity(new Intent(this, LoginUserActivity.class));
            finish();
        }else if (toastMsgMap.containsKey(2)) {//注册失败
            ToastUtil.showToast(toastMsgMap.get(2));
        }
    }

    @Override
    public void checkMobileByRegisterResult(ResultModel<ValidModel> validModelResultModel, String mobile) {
        if (validModelResultModel.isSuccess()) {
            ValidModel model = validModelResultModel.getData();
            if (model != null) {
                if (!model.isValid()) {
                    registeredMobiles.add(mobile);
                    tv_register_mobile_error.setText(R.string.register_mobile_error);
                    tv_register_mobile_error.setVisibility(View.VISIBLE);
                }
            }

        }
    }

    @Override
    public void checkEmailByRegisterResult(ResultModel<ValidModel> validModelResultModel, String email) {
        if (validModelResultModel.isSuccess()) {
            ValidModel model = validModelResultModel.getData();
            if (model != null) {
                if (!model.isValid()) {
                    registeredEmails.add(email);
                    tv_register_email_error.setText(R.string.register_email_error);
                    tv_register_email_error.setVisibility(View.VISIBLE);
                }
            }

        }
    }

}
